package com.cby.operation.pay.ui

import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.cby.operation.common.ext.getDrawableId
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ext.showToast
import com.cby.operation.common.ui.BaseDialogFragment
import com.cby.operation.common.util.ClipboardUtils
import com.cby.operation.common.util.DateUtils
import com.cby.operation.pay.PayManager
import com.cby.operation.pay.bean.PayConfig
import com.cby.operation.pay.bean.PayResult
import com.cby.operation.sdk.*
import kotlin.math.acos

/**
 * Description:该对话框是用来显示支付的结果
 *
 * @author 陈宝阳
 * @create 2020/8/6 10:10
 */
class PayResultDialogFragment : BaseDialogFragment() {
    private lateinit var payStatusIv: ImageView
    private lateinit var payStatusTv: TextView
    private lateinit var orderIdTv: TextView
    private lateinit var goodsNameTv: TextView
    private lateinit var payMoneyTv: TextView

    /**
     * 这两个控件是显示支付时间或者支付失败的原因
     */
    private lateinit var timeOrReasonTitleTv: TextView
    private lateinit var timeOrReasonTv: TextView
    private lateinit var retryBtn: TextView
    private lateinit var backBtn: TextView
    private lateinit var problemTv: TextView
    private var payResult: PayResult? = null
    private var payConfig: PayConfig? = null

    fun update(config: PayConfig?, result: PayResult?) {
        payConfig = config
        payResult = result
        setContent()
        initListener()
    }

    override fun parseArgs() {
        payConfig = arguments.getParcelable(KEY_PAY_CONFIG)
        payResult = arguments.getParcelable(KEY_PAY_RESULT)
    }

    override fun layoutName(): String {
        return "pay_result_dialog_fragment"
    }

    override fun initView(view: View?) {
        view?.let {
            payStatusIv = it.findViewById(getId("iv_pay_status"))
            payStatusTv = it.findViewById(getId("tv_pay_status"))
            orderIdTv = it.findViewById(getId("tv_order_id"))
            goodsNameTv = it.findViewById(getId("tv_goods_name"))
            payMoneyTv = it.findViewById(getId("tv_pay_money"))
            timeOrReasonTitleTv = it.findViewById(getId("tv_time_reason_title"))
            timeOrReasonTv = it.findViewById(getId("tv_time_or_reason"))
            retryBtn = it.findViewById(getId("tv_retry_btn"))
            backBtn = it.findViewById(getId("tv_back_btn"))
            problemTv = it.findViewById(getId("tv_contact_problem"))
        }

    }

    override fun setContent() {
        payStatusTv.paint.isFakeBoldText = true
        if (payResult!!.isSuccess) {
            payStatusIv.setImageResource(getDrawableId( "hykb_img_pay_success")
            )
            payStatusTv.setTextColor(Color.parseColor(COLOR_GREEN))
            payStatusTv.text = STRING_PAY_SUCCESS
            //支付成功显示支付时间
            timeOrReasonTitleTv.text = STRING_PAY_TIME
            timeOrReasonTv.text = DateUtils.getCurrentTime()
            retryBtn.visibility = View.GONE
        } else {
            //支付失败，判断是否需要显示重试按钮
            if (isShowRetry) {
                retryBtn.visibility = View.VISIBLE
            } else {
                retryBtn.visibility = View.GONE
            }
            payStatusIv.setImageResource(getDrawableId("hykb_img_pay_fail"))
            payStatusTv.setTextColor(Color.parseColor(COLOR_DEEP_DARK))
            payStatusTv.text = STRING_PAY_FAILED
            //支付失败显示失败原因
            timeOrReasonTitleTv.text = STRING_PAY_FAILED_REASON
            timeOrReasonTv.text = payResult!!.message
        }
        orderIdTv.text = payResult!!.payInfo!!.cpOrderId
        goodsNameTv.text = payResult!!.payInfo!!.goodsName
        payMoneyTv.text = getPayMoneyString(payResult!!.payInfo!!.money)
        problemTv.setTextColor(Color.parseColor(COLOR_BLUE))
        problemTv.text = STRING_ORDER_PROBLEM
    }

    private val isShowRetry: Boolean
        get() = if (payConfig != null
            && payConfig!!.payRetries != null
            && payConfig!!.payRetries!!.isNotEmpty()
            && !TextUtils.isEmpty(payResult!!.payChannel)
        ) {
            payConfig!!.payRetries!!.contains(payResult!!.payChannel)
        } else false

    override fun initListener() {
        retryBtn.setOnClickListener{
            PayManager.instance.doRetryQueryPayOrder(payResult)
            dismissAllowingStateLoss()
        }
        backBtn.setOnClickListener { // 关闭弹窗
            PayManager.instance.handlePayCallBack(payResult!!)
            dismissAllowingStateLoss()
        }
        problemTv.setOnClickListener{ updateProblem() }
    }

    /**
     * 更新疑问UI区域的文案
     */
    private fun updateProblem() {
        problemTv.setTextColor(Color.parseColor(COLOR_DARK))
        problemTv.highlightColor = Color.parseColor("#00000000")
        val contact: String = PayManager.instance.getContact()!!
        val content: String = getContactString(contact)
        val start = content.indexOf(contact)
        val end = start + contact.length
        val spannableInfo = SpannableString(content)
        spannableInfo.setSpan(PSClickableSpan {
            ClipboardUtils.copy(activity, contact)
            activity.showToast(HYKB_QQ_COPY_TIP)
        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        problemTv.text = spannableInfo
        problemTv.movementMethod = LinkMovementMethod.getInstance()
    }

    internal class PSClickableSpan(private val mListener: View.OnClickListener) : ClickableSpan() {
        override fun onClick(widget: View) {
            mListener.onClick(widget)
        }

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = Color.parseColor(COLOR_BLUE)
            ds.isUnderlineText = false
        }
    }

    companion object {
        private const val HYKB_QQ_COPY_TIP = "已复制QQ号"
        fun show(activity: Activity,
            config: PayConfig?,
            result: PayResult?
        ): PayResultDialogFragment {
            val fragment = PayResultDialogFragment()
            val data = Bundle()
            data.putParcelable(KEY_PAY_RESULT, result)
            data.putParcelable(KEY_PAY_CONFIG, config)
            fragment.arguments = data
            fragment.show(activity.fragmentManager, TAG_FRAGMENT_PAY_RESULT)
            return fragment
        }
    }
}